package jzoffer;

import leetcode.tree.TreeNode;

import java.util.*;

/**
 * @author MaoLin Wang
 * @date 2020/10/9 11:50 下午
 */
public class _32层次遍历 {
    public static int[] levelOrder(TreeNode root) {
        if (root==null){
            return new int[0];
        }
        List<Integer>res=new ArrayList<>();
        Queue<TreeNode>queue=new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode node = queue.poll();
            res.add(node.val);
            if (node.left!=null){
                queue.offer(node.left);
            }
            if (node.right!=null){
                queue.offer(node.right);
            }
        }
        int[]re=new int[res.size()];
        for (int i = 0; i < res.size(); i++) {
            re[i]=res.get(i);
        }
        return re;
    }

    public static void main(String[] args) {
        TreeNode treeNode=new TreeNode(1);
        treeNode.left=new TreeNode(2);
        treeNode.right=new TreeNode(3);
        treeNode.left.left=new TreeNode(4);
        treeNode.left.right=new TreeNode(5);
        int[] ints = levelOrder(treeNode);
        for (int anInt : ints) {
            System.out.println(anInt);
        }
    }
}
